<template>
    <div class="search-container">
        <!-- 搜索框 -->
        <form action="/">
            <van-search
                v-model="searchText"
                autofocus
                show-action
                background="#2892ff"
                placeholder="请输入搜索关键词"
                @search="onSearch(searchText)"
                @cancel="$router.back()"
                @focus="isShowResult = false"
            />
        </form>
        <!-- 搜索内容 -->
        <SearchResult v-if="isShowResult"
            :search-text="searchText"
        />
        <!-- 联想建议 -->
        <SearchSuggestion
            v-else-if="searchText"
            :search-text="searchText"
            @search="onSearch"
        />
        <!-- 历史记录 -->
        <SearchHistory
            v-else
            :history-list="historyList"
            @search="onSearch"
            @resetHistories="historyList=$event"
        />
    </div>
</template>

<script>
import { mapState } from 'vuex';
import SearchSuggestion from 'com/search/search_suggestion';
import SearchHistory from 'com/search/search_history';
import SearchResult from 'com/search/search_result';
import { getItem, setItem } from '@/utils/storage';
// import * as Api from 'api/common';

export default {
    name: 'search',
    components: {
        SearchSuggestion,
        SearchHistory,
        SearchResult
    },
    // 定义属性
    data () {
        return {
            searchText: '',
            isShowResult: false,
            historyList: []
        };
    },
    // 计算属性，会监听依赖属性值随之变化
    computed: {
        ...mapState(['user'])
    },
    // 监控data中的数据变化
    watch: {
        historyList () {
            // 历史记录持久化
            setItem('search-histories', this.historyList);
        }
    },
    // 方法集合
    methods: {
        onSearch (searchText) {
            this.searchText = searchText; // 主要目的是接收从联想建议组件选中的搜索值
            let index = this.historyList.indexOf(searchText);
            if (index !== -1) this.historyList.splice(index, 1);
            this.historyList.unshift(searchText);
            // // 历史记录持久化
            // setItem('search-histories', this.historyList);
            this.isShowResult = true;
        },
        async loadSearchHistories () {
            let searchHistories = getItem('search-histories') || [];
            // if (this.user) {
            //     const res = await Api.reqDev('/v1_0/search/histories');
            //     if (res.message === 'OK') {
            //         searchHistories = [...new Set(searchHistories.concat(res.data.keywords))];
            //     }
            // }
            this.historyList = searchHistories;
        }
    },
    // 生命周期 - 创建完成（可以访问当前this实例）
    created () {
        this.loadSearchHistories();
    },
    // 生命周期 - 挂载完成（可以访问DOM元素）
    mounted () {
    }
};
</script>

<style lang='less' scoped>
.search-container {
    .van-search {
        .van-search__action {
            color: #fff;
        }
    }
}
</style>
